package ru.nlezhnev.utils;

import java.io.UnsupportedEncodingException;

import ru.nlezhnev.Constants;
import flex.messaging.io.amf.ASObject;

public class FarmRequest {
	private ASObject data;
	private int uid;
	private boolean isSecure;
	
	public FarmRequest(byte[] request, String clientMd5) {
		data = RequestDecoder.decode(request);
		uid = (Integer)data.get("uid");
		
		try {			
			isSecure = checkDataSecure(request, getSecureKey().getBytes("UTF-8"), clientMd5);
			
			if (!isSecure && !Constants.PRODUCTION_SERVER) {
				isSecure = checkDataSecure(request, Constants.SECURE_KEY.getBytes("UTF-8"), clientMd5);	
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public ASObject getData() {
		return data;
	}
	
	public int getUid() {
		return uid;
	}
	
	public boolean isCheckFailed() {
		return !isSecure;
	}
	
	private boolean checkDataSecure(byte[] data, byte[] secure_bytes, String clientMd5) {
		byte coded_request[] = new byte[secure_bytes.length + data.length];
		System.arraycopy(secure_bytes, 0, coded_request, 0, secure_bytes.length);
		System.arraycopy(data, 0, coded_request, secure_bytes.length, data.length);
		
		String serverMd5 = MD5.hashBinary(coded_request);
		return serverMd5.equals(clientMd5);
	}
	
	private String getSecureKey() {
		return Constants.API_ID + "_" + Integer.toString(uid) + "_" + Constants.API_SECRET;
	}
}
